<template>
  <div class="search-div">
    <!-- 搜索表单 -->
    <el-form label-width="70px" size="small">
      <el-form-item label="角色名称">
        <el-input
          style="width: 100%"
          placeholder="角色名称"
          v-model="queryDto.roleName"
        ></el-input>
      </el-form-item>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="searchSysRole">
          搜索
        </el-button>
        <el-button size="small" @click="resetSysRole">重置</el-button>
      </el-row>
    </el-form>

    <!-- 添加按钮 -->
    <div class="tools-div">
      <el-button type="success" size="small" @click="showAddDialog">
        添 加
      </el-button>
    </div>
    <!-- 添加角色表单对话框 -->
    <el-dialog v-model="dialogVisible" title="添加或修改角色" width="30%">
      <el-form label-width="120px">
        <el-form-item label="角色名称">
          <el-input v-model="addRoleDto.roleName" />
        </el-form-item>
        <el-form-item label="角色Code">
          <el-input v-model="addRoleDto.roleCode" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleDto.description" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddSysRole">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--- 角色表格数据 -->
    <el-table :data="list" style="width: 100%">
      <el-table-column prop="roleName" label="角色名称" width="180" />
      <el-table-column prop="roleCode" label="角色code" width="180" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column label="操作" align="center" width="280" #default="scope">
        <el-button type="primary" size="small" @click="editSysRole(scope.row)">
          修改
        </el-button>
        <el-button
          type="danger"
          size="small"
          @click="deleteSysRoleById(scope.row.id)"
        >
          删除
        </el-button>
        <el-button
          type="warning"
          size="small"
          @click="showAssignMenu(scope.row)"
        >
          分配菜单
        </el-button>
      </el-table-column>
    </el-table>
    <!-- 分配菜单的对话框 
// tree组件添加ref属性，后期方便进行tree组件对象的获取
-->
<el-dialog v-model="dialogMenuVisible" title="分配菜单" width="40%">
    <el-form label-width="80px">
        <el-tree
                 :data="sysMenuTreeList"
                 ref="tree"   
                 show-checkbox
                 default-expand-all
                :default-checked-keys="selectKeys"
                 :check-on-click-node="true"
                 node-key="id"
                 :props="defaultProps"
        />
        <el-form-item>
            <el-button type="primary" @click="submitDoAssign">提交</el-button>
            <el-button @click="dialogMenuVisible = false">取消</el-button>
        </el-form-item>
    </el-form>
</el-dialog>

    <!--分页条-->
    <el-pagination
      v-model:current-page="pageParams.page"
      v-model:page-size="pageParams.limit"
      :page-sizes="[2, 5, 10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  selectRoleByPage,
  addRole,
  edit,
  removeSysRoleById,
  getMenuAndMenuId,
  assignMenu
} from '@/api/sysRole'
import { ElMessage, ElMessageBox } from 'element-plus'
//定义给角色新增菜单的dto
const defualtAssignForm={
    roleId:'',
    menuIdList:[
        {
            "menuId":'',
            "isHalf":''
        }
    ]
}
const assignMenuDto=ref(defualtAssignForm)

const addDoAssign=()=>{
    //获取选择的菜单的id
  const checkedNode=  tree.value.getCheckedNodes()
  //遍历过滤需要的数据［｛id:1｝，｛id:2｝］
  const checkedNodeIds=checkedNode.map(node=>{
      return {
        menuId:node.id,
        isHalf:0
      }
  })
//   console.log(checkedNode)
//   console.log(checkedNodeIds)
  //getHalfCheckedNodes
  //获取办选中的菜单id
      //获取选择的菜单的id
      const checkedHalfNode=  tree.value.getHalfCheckedNodes()
  //遍历过滤需要的数据［｛id:1｝，｛id:2｝］
  const checkedHalfNodeIds=checkedHalfNode.map(node=>{
      return {
        menuId:node.id,
        isHalf:1
      }
  })
//   console.log(checkedHalfNode)
//   console.log(checkedHalfNodeIds)
  //合并全选中和半选中
  const menuIdList=[...checkedNodeIds,...checkedHalfNodeIds]
  console.log(menuIdList)
  //赋值给响应式对象
  assignMenuDto.value.menuIdList=menuIdList

  
}
//提交给角色新增的菜单
const submitDoAssign=async()=>{
   // console.log(assignMenuDto.value.roleId)
    //封装数据
    addDoAssign()
   const {code}= await assignMenu(assignMenuDto.value)
   if(code===200){
      ElMessage.success("添加成功")
   }
   //关闭对话框
   dialogMenuVisible.value=false
   //刷新页面
   showRoleByPage()
   

}
//回显,已经拥有的id
const selectKeys=ref([])
// //定义树对象模型
const tree=ref()
//显示菜单标题的属性
const defaultProps = ref({
  children: 'children',
  label: 'title',
})
//分配菜单的回显数据
const sysMenuTreeList=ref([])
//分配菜单对话框显示
const dialogMenuVisible=ref(false)
//
const showAssignMenu=async(row)=>{
    //拿到当前rid, 添加的时候使用
    assignMenuDto.value.roleId=row.id


     
    
    //查询全部菜单
    const {data}=await getMenuAndMenuId(row.id)
    sysMenuTreeList.value=data.sysMenuList;
    
    selectKeys.value=data.holdMenuIds
    dialogMenuVisible.value=true
  

}
// 删除角色
const deleteSysRoleById = id => {
  //防止用户误删,给个提示
  ElMessageBox.confirm('确定要删除吗', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true,
  })
    .then(async () => {
      // 用户确定 根据id 向后段发送请求
      const { code } = await removeSysRoleById(id)
      // 成功后给出提示信息,并刷新数据
      if (code === 200) {
        ElMessage({
          type: 'success',
          message: ' 删除成功',
        })
        //刷新数据
        showRoleByPage()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

//修改
const editSysRole = async row => {
  // //显示对话框
  dialogVisible.value = true
  // 回显数据
  addRoleDto.value = row
}
const submitAddSysRole = async () => {
  // 判断是新增还是修改 看id有没有内容
  if (!addRoleDto.value.id) {
    // 新增
    const { code } = await addRole(addRoleDto.value)

    if (code == 200) {
      // 显示新增成功的提示信息
      //     ElMessage({
      //     message: '添加成功',
      //     type: 'success',
      // })

      //    也可以用这种写法
      ElMessage.success('添加成功')

      //    隐藏对话框
      dialogVisible.value = false
      // 重新查询一次
      showRoleByPage()
    }
  } else {
    const { code } = await edit(addRoleDto.value)
    if (code === 200) {
      // 隐藏对话框
      dialogVisible.value = false
      // addRoleDt={} // 数据清空
      //提示成功
      // ElMessage.success("修改成功")
      ElMessage.success('修改成功')
      //清除响应式数据, 防止添加的时候还有数据
      addRoleDto.value = {}
    }
  }
}

const defaultAddRole = {
  id: '', //id用来完成修改操作
  roleName: '',
  roleCode: '',
  description: '',
}
// 声明为响应式对象
const addRoleDto = ref(defaultAddRole)
// 新增对话框是否显示控制
const dialogVisible = ref(false)
const showAddDialog = () => {
  dialogVisible.value = true
}
const handleSizeChange = () => {
  showRoleByPage()
}
const handleCurrentChange = () => {
  showRoleByPage()
}
// 搜索
const searchSysRole = () => {
  showRoleByPage()
}
// 重置搜索条件
const resetSysRole = () => {
  queryDto.value.roleName = null
  showRoleByPage()
}
//设置分页初始化数据
const defaultPageInfoForm = {
  page: 1, //当前页
  limit: 10, //每页有多少条数据
}
//设置为响应式数据
const pageParams = ref(defaultPageInfoForm)
//初始化查询条件
const queryDto = ref({
  roleName: '',
})
onMounted(() => {
  // 箭头表达式 空参或者多个参数需要加括号, 如果就一个参数可以不加括号
  showRoleByPage()
})
const showRoleByPage = async () => {
  const { data, code, message } = await selectRoleByPage(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  if (code === 200) {
    total.value = data.total
    list.value = data.list
  }
}

// 分页条总记录数
let total = ref(0)

// 定义表格数据模型
let list = ref([
  {
    id: 9,
    roleName: '系统管理员',
    roleCode: 'xtgly',
    createTime: '2023-07-31',
  },
  {
    id: 10,
    roleName: '商品管理员',
    roleCode: 'spgly',
    createTime: '2023-07-31',
  },
])
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
</style>
